package cn.edu.stu.contorller.common;

import cn.edu.stu.bean.AjaxResult;
import cn.edu.stu.service.ConfService;
import cn.edu.stu.tool.Base64;
import cn.edu.stu.tool.Constants;
import cn.edu.stu.tool.JWTUtil;
import com.google.code.kaptcha.Producer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Karl
 * @Date 2022/12/11 - 19:48
 */
@Controller
public class CaptchaController {

    @Autowired
    ConfService confService;

    @Resource(name = "captchaProducerChar")
    Producer captchaProducerChar;

    @Resource(name = "captchaProducerMath")
    Producer captchaProducerMath;

    @GetMapping("/captchaImage")
    @ResponseBody
    public AjaxResult getCode(){
        AjaxResult result = AjaxResult.success();
        boolean captchaOnOff = confService.selectCaptchaOnOff();
        result.put("captchaOnOff",captchaOnOff);
        if(!captchaOnOff){
            return result;
        }

        //生成验证码信息
        String capStr = null,code = null;
        BufferedImage image = null;

        switch (confService.getCaptchaType()){
            case "char":
                String capText1 = captchaProducerChar.createText();
                capStr = capText1;
                code = capText1;
                image = captchaProducerChar.createImage(capStr);
                break;
            case "math":
            default:
                String capText = captchaProducerMath.createText();
                capStr = capText.substring(0,capText.lastIndexOf('@'));
                code = capText.substring(capText.lastIndexOf('@')+1);
                image = captchaProducerMath.createImage(capStr);
                break;
        }

        long l = System.currentTimeMillis();
        Map<String,String> map = new HashMap<>();
        map.put(Constants.CAPTCHA_CODE_KEY,code);
        String token = JWTUtil.createToken(map);
//        map.put(Constants.CAPTCHA_EXPIRATION_KEY,l+Constants.CAPTCHA_EXPIRATION);
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        try {
            ImageIO.write(image,"jpg",os);

        } catch (IOException e) {
            return AjaxResult.error(e.getMessage());
        }
        result.put("img", Base64.encode(os.toByteArray()));
        result.put("token",token);
        return result;
    }
}
